//
//  ChatDB.m
//  projectOfTeamSample
//
//  Created by lanou3g on 15/11/20.
//  Copyright © 2015年 liukai. All rights reserved.
//

#import "ChatDB.h"
#import <sqlite3.h>
#import "ChatModel.h"
@implementation ChatDB
//单例
static ChatDB * manager = nil;
+ (instancetype)manager{
    @synchronized(self) {
        if (manager ==  nil) {
            manager = [[ChatDB alloc]init];
        }
    }
    return manager;
}
//打开数据库
static sqlite3 *DB = nil;
- (BOOL)openChetDB{
    //数据库路径
    NSString *documents = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *sqlpath = [documents stringByAppendingPathComponent:@"chat.sqlite"];
    NSLog(@"数据库路径%@",sqlpath);
    //判断是否打开数据库成功
    int result = sqlite3_open(sqlpath.UTF8String, &DB) ;
    if (result == SQLITE_OK) {
        NSLog(@"打开数据库成功");
        return YES;
    }else{
        NSLog(@"打开数据库失败");
        return NO;
    }
}
//关闭数据库
- (void)closeChatDB{
    int resule = sqlite3_close(DB);
    if (resule == SQLITE_OK) {
        NSLog(@"关闭数据库成功");
    }else{
        NSLog(@"关闭数据库失败");
    }
}
//创建表

- (void)creatTable{
    //
    NSString *sqlStr = @"CREATE TABLE chat (id INTEGER PRIMARY KEY AUTOINCREMENT, chatManager  TEXT, client TEXT) ";
    //数据库路径
    int result = sqlite3_exec(DB, sqlStr.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"创建表成功");
    }else{
        NSLog(@"创建表失败");
    }
}

//添加数据
- (void)insertWithText:(NSString *)text WithId:(NSString *)client{
    NSString *string = [NSString stringWithFormat:@"INSERT INTO chat (chatManager,client ) VALUES ('%@','%@')",text,client];
    
    int result = sqlite3_exec(DB,string.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"插入成功");
    }else{
        NSLog(@"插入失败");
        return;
    }
}
//查询所有的聊天记录,在刚进入的时候显示
- (NSMutableArray *)seleteAll{
    NSString *sql = @"SELECT * FROM chat";
    //一个命令指针
    sqlite3_stmt *stmt = nil;
    //sql语句预执行
    int prepareResult = sqlite3_prepare(DB, sql.UTF8String, -1, &stmt,NULL);
    NSMutableArray *Array = [[NSMutableArray alloc]init];
    
    
    if (prepareResult == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {

            ChatModel *chatModel = [[ChatModel alloc]init];
            chatModel.chatMassage = [NSString stringWithUTF8String:(const char*)sqlite3_column_text(stmt, 1)];
            chatModel.client = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 2)];
            [Array addObject:chatModel];

        }
        sqlite3_finalize(stmt);
        return Array;
    }else{
        NSLog(@"预执行失败");
    }
    return nil;
}
@end
